﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using CounterServerModel;
using System.Globalization;


namespace SmartCounters
{
	public partial class UsageInformation : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			((MainTemplate)Master).m_PagePermissionFilter = MainTemplate.k_UserPageFilter;
		}
		
		protected void Page_Prerender(object sender, EventArgs e)
		{
            if (!this.IsPostBack)
            {
				populateDropDownList();
				tbStartDate.Text = (DateTime.Now.AddMonths(-1)).ToString("dd/MM/yyy");
				tbEndDate.Text = (DateTime.Now).ToString("dd/MM/yyy");
				
				if (Request.QueryString["AccountID"] != null)
				{
					ddAcounts.Items.FindByValue(Request.QueryString["AccountID"]).Selected = true;
				}

				showChart();
            }
		}

		private void populateDropDownList()
		{
			ddAcounts.Items.Clear();
			List<AccountInfo> accounts = new List<AccountInfo>();
			InformationReader reader = new InformationReader();
			UserInfo userInfo = reader.GetUserInformation(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, ((MainTemplate)Master).AuthenticatedLoggedInUserCredentials.ID);
			if ((userInfo.UserPermissions & eUserPermissions.ReadOtherBill) == eUserPermissions.ReadOtherBill)
			{
				accounts = reader.GetAllAccounts(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials);
			}
			else if ((userInfo.UserPermissions & eUserPermissions.ReadOwnBill) == eUserPermissions.ReadOwnBill)
			{
				foreach (int accountID in userInfo.AccountsAssociatedWith)
				{
					accounts.Add(reader.GetAccountInformation(((MainTemplate)Master).AuthenticatedLoggedInUserCredentials, accountID));
				}
			}

			foreach (AccountInfo accountInfo in accounts)
			{
				string accountLable = accountInfo.Country + " " + accountInfo.City + " " + accountInfo.Street + " " + accountInfo.House + "/" + accountInfo.Apartment;
				ddAcounts.Items.Add(new ListItem(accountLable, accountInfo.AccountID.ToString()));
			}
		}

        protected void btShowAllUsages_Click(object sender, EventArgs e)
        {
            chart.Visible = false;
            usagesGrid.Visible = true;

            int accountID = int.Parse(ddAcounts.SelectedItem.Value);
            BillingService billingService = new BillingService();

			DateTime fromDate = DateTime.ParseExact(tbStartDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
			DateTime toDate = DateTime.ParseExact(tbEndDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

			DataTable usages = billingService.GetUsagesTable(
                ((MainTemplate)Master).AuthenticatedLoggedInUserCredentials,
                accountID,
				fromDate.Year,
				fromDate.Month,
				fromDate.Day,
				toDate.Year,
				toDate.Month,
				toDate.Day);

            usagesGrid.DataSource = usages;
            usagesGrid.DataBind();
        }

        protected void btShowChart_Click(object sender, EventArgs e)
        {
			showChart();
        }

        private void showChart()
        {
			chart.Visible = true;
			usagesGrid.Visible = false;

			int accountID = int.Parse(ddAcounts.SelectedItem.Value);
			BillingService billingService = new BillingService();

			DateTime fromDate = DateTime.ParseExact(tbStartDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
			DateTime toDate = DateTime.ParseExact(tbEndDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

			DataTable usages = billingService.GetUsagesTable(
				((MainTemplate)Master).AuthenticatedLoggedInUserCredentials,
				accountID,
				fromDate.Year,
				fromDate.Month,
				fromDate.Day,
				toDate.Year,
				toDate.Month,
				toDate.Day);

            int difference = usages.Rows.Count / 100 != 0 ? usages.Rows.Count / 100 : 1;

            for (int i = 0; i < usages.Rows.Count; i += difference)
            {
                chart.Series[0].Points.AddXY(DateTime.Parse(usages.Rows[i]["UpdateDate"].ToString()), double.Parse(usages.Rows[i]["TotalUsage"].ToString()));
            }

			chart.DataBind();
        }
	}
}